package com.ruoyi.yl.rocketmq.product;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.domain.constant.enums.MessTopicAndTag;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;


@Component
public class MessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送普通消息
     */
    public void sendMessage(String topic, String message) {
        rocketMQTemplate.convertAndSend(topic, message);
    }

    /**
     * 发送带Tag的消息
     */
    public void sendMessageWithTag(String topic, String tag, String message) {
        rocketMQTemplate.convertAndSend(topic + ":" + tag, message);
    }

    /**
     * 发送事务消息
     */
    public void sendTransactionMessage(String topic, String message, Object arg) {

        rocketMQTemplate.sendMessageInTransaction(topic,
                MessageBuilder.withPayload(message).build(), arg);
    }


    /**
     * rocketmq.productGroup 在yml中配置 对应发送端
     * topic: 消息一级分类筛选
     * selectorExpression: tag 对应二级分类筛选  pay||reback 支持这种语法
     * 你也可以在消费者中获取 进行业务区分
     *
     */
    public void sendDelayMessage(String topic,String tag, String message) {
        rocketMQTemplate.syncSendDelayTimeSeconds(
                topic+":"+tag,
                MessageBuilder.withPayload(message)
                        .setHeader("key1","test1")
                        .setHeader("key2","test3")
                        .build(),
                3);
    }

    /**
     * 发送JSON字符串
     * @param topicAndTag  枚举定类
     * @param message 消息
     * @param delayTime 秒
     */
    public  void sendDelayMessageObj(MessTopicAndTag topicAndTag, Object message, Long delayTime) {
        rocketMQTemplate.syncSendDelayTimeSeconds(
                topicAndTag.getTopic()+":"+topicAndTag.getTag(),
                MessageBuilder.withPayload(JSON.toJSONString(message))
                        .build(),
                delayTime);
    }

    /**
     * 发送JSON字符串
     * @param topicAndTag  枚举定类
     * @param message 消息
     */
    public void sendMessageWithTagObj(MessTopicAndTag topicAndTag, Object message) {
        rocketMQTemplate.convertAndSend(topicAndTag.getTopic() + ":" + topicAndTag.getTag(), JSON.toJSONString(message));
    }
}